﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MainRole : Role
{
    SelectMgr _selectMgr = new SelectMgr();
    public Creature CurTarget;

    public override void Init(CreateSenceCreature serverData, CreatureDatabase tableData)
    {
        base.Init(serverData, tableData);
        //绑定控制事件（隐含的要求：UI创建要比主角早 ）
        //主角设置一个单独的层
        gameObject.layer = GameSetting.MainRoleLayer;
        bindingControlEvent();
        _selectMgr.Init(this);
        _skillMgr.AutoSelectCallback += selectCreature;
    }

    public void onJumpTo(int jumpToMap)
    {
        Client.GetInstance().SendCmd(new JumpToCmd() { ID = jumpToMap });
    }

    private void bindingControlEvent()
    {
        FightUIMgr.GetInstance().BindingJoystick(OnJoystickMove, OnJoystickMoveEnd);
        FightUIMgr.GetInstance().BindingTouchScene(OnTouchSomething,LayerMask.NameToLayer("MainRole"));
        FightUIMgr.GetInstance().BindingSkillBtn(onSkill,updateSkillCDPercent);
    }
    private void onSkill(int index)
    {
        CastSkill(index);
    }
    private float updateSkillCDPercent(int index)
    {
        return getSkillCDPercent(index);
    }

 
    private void OnTouchSomething(RaycastHit hitRet)
    {
        selectCreature(null);
        var hitObj = hitRet.transform.gameObject;
        //点击地面
        if (hitObj.layer == LayerMask.NameToLayer("Ground"))
        {
            TouchGroundPathTo(hitRet.point);
            return;
        }
        var creature = hitObj.GetComponent<Npc>();
        //点击npc
        if (creature != null)
        {
            //选中npc
            selectCreature(creature);
            var npc = creature as Npc;
            if(npc == null)
            {
                return;
            }
            if (!npc.IsFuncNPC) { return; }
            PurposeTo(creature.transform.position, 1, () => onVisitNpc(npc));
            return;
        }
    }

    private void selectCreature(Creature creature)
    {
        _selectMgr.Select(creature);
    }

    private void onVisitNpc(Npc npc)
    {
        Debug.Log("visit:" + npc.Name);
    }

    private void OnJoystickMoveEnd()
    {
        StopMove();

    }
    private void OnJoystickMove(Vector2 dir)
    {
        var speed = 1;//速度与目标点的校验值，与速度正相关，与方向更新频率负相关
        var target = this.transform.position + new Vector3(dir.x, 0, dir.y) * speed;
        JoystickMove(target);
    }


}
